﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Core.Helper;
using Core.Model;
using log4net;

namespace DataServer.View
{
    /// <summary>
    /// CommandExcute.xaml 的交互逻辑
    /// </summary>
    public partial class CommandExcute
    {
        private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private Channel _selectChannel;
        private Device _selectDevice;
        private Operation _selectOperation;
        private string _parameter = "";
        private readonly ObservableCollection<Channel> channels = new ObservableCollection<Channel>();
        private readonly ObservableCollection<Device> devices = new ObservableCollection<Device>();
        private readonly ObservableCollection<Operation> operations = new ObservableCollection<Operation>();


        private readonly DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal);
        public CommandExcute()
        {
            InitializeComponent();
            this.Loaded += CommandExcute_Loaded;
           
        }
        private void CommandExcute_Loaded(object sender, RoutedEventArgs e)
        {
            timer.Interval = TimeSpan.FromSeconds(3);
            timer.Tick += Timer_Tick;
            timer.Start();
            cbbChannel.ItemsSource = channels;
            cbbDevice.ItemsSource = devices;
            cbbOperate.ItemsSource = operations;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            timer.Tick -= Timer_Tick;
            try
            {
                channels.Clear();
                var list = AppManager.ChannelDao.GetEntities();
                foreach (Channel channel in list)
                {
                    channels.Add(channel);
                }

                if (channels.Count > 0)
                {
                    cbbChannel.SelectedItem = channels[0];
                }
            }
            catch (Exception ex)
            {
                _log.Error("命令测试加载异常:"+ex.Message);
            }
        }


        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+"\r\n";
            RequetResult.Text = date;
            if (_selectChannel != null && _selectDevice != null && _selectOperation != null)
            {
                string url = $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}";
                if (!string.IsNullOrEmpty(_parameter))
                {
                    url = $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}&paras={_parameter}";
                }
                try
                {
                    string result = NetHelper.HttpGet(url);
                    RequetResult.Foreground = Brushes.DarkGreen;
                    RequetResult.Text = date+JsonHelper.JsonTree(result);
                }
                catch (Exception ex)
                {
                    RequetResult.Foreground = Brushes.Red;
                    RequetResult.Text = date+"异常:" + ex.Message;
                }
            }
            else
            {
                RequetResult.Foreground = Brushes.Orange;
                RequetResult.Text = date+"请选择参数!";
            }
           
        }

        private void CbbChannel_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            devices.Clear();
            operations.Clear();
            _parameter = "";
            _selectChannel = cbbChannel.SelectedItem as  Channel;
            if (_selectChannel != null)
            {
                try
                {
                    List<Device> devs = AppManager.DeviceDao.GetDevicesByChlId(_selectChannel.Id);
                    foreach (Device dev in devs)
                    {
                        devices.Add(dev);
                    }
                    if (devices.Count > 0)
                    {
                        cbbDevice.SelectedItem = devices[0];
                    }
                }
                catch (Exception ex)
                {
                    RequetResult.Foreground = Brushes.Orange;
                    RequetResult.Text = "获取通道中的设备信息异常:" + ex.Message;
                }
            }
        }

        private void CbbDevice_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            operations.Clear();
            _parameter = "";
            _selectDevice = cbbDevice.SelectedItem as  Device;
            if (_selectDevice != null)
            {
                try
                {
                    List<Operation> opers = AppManager.OperationDao.GetOperationByDevType(_selectDevice.DeviceTypeId);
                    if (opers == null) return;
                    foreach (Operation oper in opers)
                    {
                        operations.Add(oper);
                    }
                    if (operations.Count > 0)
                    {
                        cbbOperate.SelectedItem = operations[0];
                    }
                }
                catch (Exception ex)
                {
                    RequetResult.Foreground = Brushes.Orange;
                    RequetResult.Text = "获取设备的操作信息异常:" + ex.Message;
                }
            }
        }

        private void CbbOperate_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cbbOperate.ToolTip = "";
            _parameter = "";
            txtParameter.Text = "";
            _selectOperation = cbbOperate.SelectedItem as Operation;
            if (_selectChannel != null && _selectDevice != null && _selectOperation != null)
            {
                cbbOperate.ToolTip = _selectOperation.MsgContent;
                string url =
                    $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}";
                if (!string.IsNullOrEmpty(_parameter))
                {
                    url =
                        $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}&paras={_parameter}";
                }
                txtTargetUrl.Text = url;
            }
        }
    
        private void TxtParameter_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            _parameter = txtParameter.Text;
            if (_selectChannel != null && _selectDevice != null && _selectOperation != null)
            {
                string url =
                    $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}";
                if (!string.IsNullOrEmpty(_parameter))
                {
                    url =
                        $"http://localhost/control/command/excute?chlid={_selectChannel.Id}&devid={_selectDevice.Id}&operid={_selectOperation.Id}&paras={_parameter}";
                }
                txtTargetUrl.Text = url;
            }
        }
    }

}
